import { ref, reactive, computed } from "vue";

import { toast } from "~/composables/util";

// 1、对搜索、列表分页、删除/批量删除和修改状态进行封装
export function useInitTable(opt = {}) {
  // 搜索管理员表单
  let searchForm = null;
  // 重置搜索管理员表单
  let resetSearchForm = null;
  if (opt.searchForm) {
    searchForm = reactive({ ...opt.searchForm });
    resetSearchForm = () => {
      for (const key in opt.searchForm) {
        searchForm[key] = opt.searchForm[key];
      }
      getData();
    };
  }

  const tableData = ref([]);

  // 加载动画
  const loading = ref(false);

  // 当前页码
  const currentPage = ref(1);
  // 数据总条数
  const total = ref(0);
  //  每页显示多少条数据
  const limit = ref(10);

  // 获取数据
  function getData(p = null) {
    // 获取的是页码
    console.log("current-change:", p);
    if (typeof p == "number") {
      currentPage.value = p;
    }
    loading.value = true;
    opt
      .getList(currentPage.value, searchForm)
      .then((res) => {
        // 如果回调函数存在就执行回调函数
        if (opt.onGetListSuccess && typeof opt.onGetListSuccess == "function") {
          opt.onGetListSuccess(res);
        } else {
          // 不传回调走默认赋值
          tableData.value = res.list;
          total.value = res.totalCount;
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }

  getData();

  // 删除公告
  const handleDelete = (id) => {
    console.log("删除公告：", id);
    opt
      .delete(id)
      .then((res) => {
        toast("删除成功");
        getData();
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 修改状态
  const handleStatusChange = (status, row) => {
    console.log(status);
    row.statusLoading = true;
    opt
      .updateStatus(row.id, status)
      .then((res) => {
        toast("修改状态成功");
        // 这么写就不需要重新获取列表数据就可以实现回显了
        row.status = status;
      })
      .finally(() => {
        row.statusLoading = false;
      });
  };

  // 表格多选
  const multiSelectionIds = ref([]);
  const handleSelectionChange = (e) => {
    // console.log("表格多选:",e.map(o=>o.id));
    multiSelectionIds.value = e.map((o) => o.id);
  };

  const multipleTableRef = ref(null);

  // 批量删除
  const handleMultiDelete = () => {
    loading.value = true;
    opt
      .delete(multiSelectionIds.value)
      .then((res) => {
        toast("删除成功！");
        // 清空选中
        if (multipleTableRef.value) {
          multipleTableRef.value.clearSelection();
        }
        getData();
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 批量修改状态
  const handleMultiStatusChange = (status) => {
    loading.value = true;
    opt
      .updateStatus(multiSelectionIds.value, status)
      .then((res) => {
        toast("修改状态成功！");
        // 清空选中
        if (multipleTableRef.value) {
          multipleTableRef.value.clearSelection();
        }
        getData();
      })
      .finally(() => {
        loading.value = false;
      });
  };

  return {
    searchForm,
    resetSearchForm,
    tableData,
    loading,
    currentPage,
    total,
    limit,
    getData,
    handleDelete,
    handleStatusChange,
    handleSelectionChange,
    multipleTableRef,
    handleMultiDelete,
    handleMultiStatusChange,
    multiSelectionIds,
  };
}

// 2、新增和修改进行封装
export function useInitForm(opt = {}) {
  // 表单部分
  const formDrawerRef = ref(null);
  const formRef = ref(null);
  const defaultForm = opt.form;
  const form = reactive({});
  const rules = opt.rules || {};

  // 右侧新增和修改共用一个右侧弹窗，这里使用变量区别
  // editId为0表示新增 否则表示修改
  const editId = ref(0);
  const drawerTitle = computed(() => (editId.value ? "修改" : "新增"));

  // 右侧新增和修改共用一个右侧弹窗，这里使用变量区别
  // editId为0表示新增 否则表示修改

  // 新增公告 提交右侧表单弹窗的数据
  const handleSubmit = () => {
    formRef.value.validate((valid) => {
      if (!valid) return;
      formDrawerRef.value.showLoading();

      let body = {};
      if (opt.beforeSubmit && typeof opt.beforeSubmit == "function") {
        body = opt.beforeSubmit({ ...form });
      } else {
        body = form;
      }

      const fun = editId.value
        ? opt.update(editId.value, body)
        : opt.create(body);

      fun
        .then((res) => {
          console.log("新增公告：", res);
          toast(drawerTitle.value + "成功！");
          // 如果是修改就刷新当前页，如果是新增就重新刷新第一页
          opt.getData(editId.value ? false : 1);
          formDrawerRef.value.close();
        })
        .finally(() => {
          formDrawerRef.value.hideLoading();
        });
    });
  };

  // 重置(回显)右侧表单弹窗
  function restForm(row = false) {
    if (formRef.value) formRef.value.clearValidate();
    // 如果是修改，我们在这里对表单数据进行回显
    for (const key in defaultForm) {
      form[key] = row[key];
    }
  }
  // 新增公告 打开右侧表单弹窗
  const handleCreate = () => {
    editId.value = 0;
    // 新增时，对表单数据进行初始化
    restForm(defaultForm);
    formDrawerRef.value.open();
  };

  // 修改公告
  const handleEdit = (row) => {
    console.log("handleEdit:", row);
    editId.value = row.id;
    console.log("表单标题：", drawerTitle.value);
    restForm(row);
    formDrawerRef.value.open();
  };

  return {
    formDrawerRef,
    formRef,
    form,
    rules,
    editId,
    drawerTitle,
    handleSubmit,
    restForm,
    handleCreate,
    handleEdit,
  };
}
